#include "conn.h"

void *conn_thread(void *arg) 
{
	conn_t				*conn;
	global_t			*global;
	struct sockaddr_in 	servaddr;
	char				header[MAX_HEADER], *ip_str, *url_str;
	int					n;

	global = (global_t *)arg;

	printf("新一轮的connect...\n");
	printf("wait url...url size = %d\n", q_size(global->url_queue));
	sem_wait(&global->usem);
	printf("等到一个url...\n");
	url_str = (char *)q_pop(global->url_queue);
	ip_str = ht_find(global->host_table, url_get_host(url_str));
	if (ip_str == NULL) {
		return (void *)0;
	}

	printf("wait conn...\n");
	sem_wait(&global->csem);
	printf("等到一个conn...\n");
	conn = (conn_t *)q_pop(global->conn_queue);

	init_conn(conn, url_str);

	// 连接服务器
	if ((conn->sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		printf("socket 出错...%s\n", conn->url);
		q_push(global->conn_queue, conn);
		sem_post(&global->csem);
		return (void *)0;
	}
	printf("socket成功...\n");

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(80);
	inet_pton(AF_INET, ip_str, &servaddr.sin_addr);
	if (connect(conn->sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) {
		printf("connect 出错...%s\n", conn->url);
		q_push(global->conn_queue, conn);
		sem_post(&global->csem);
		return (void *)0;
	}
	printf("connect成功...\n");

	// 发送request报文
	sprintf(header, "GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: kcrawler\r\n\r\n",
			url_get_path(conn->url), url_get_host(conn->url));
	debug("%s", header);
	n = write(conn->sockfd, header, strlen(header));
	//debug("sockfd = %d, write %d bytes to %s\n\n", conn->sockfd, n, conn->url);

	list_add(global->dl_list, conn);
	printf("添加一个dl conn....\n");
	sem_post(&global->dsem);

	printf("request成功...\n");

	return (void *)0;
}

void init_conn(conn_t *conn, char *url_str)
{
	conn->url = url_str;
	conn->nread = 0;
	conn->length = 0;
	conn->header_finish = 0;
}

void free_conn(global_t *global, conn_t *conn)
{
	conn->nread = 0;
	conn->length = 0;
	conn->header_finish = 0;
	close(conn->sockfd);
}
